﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using System.Web.Caching;
using System.Net;
using System.IO;
using System.Text;
using LitJson;


/// <summary>
/// eHelper 的摘要说明
/// </summary>
public class eFHelper
{
	public eFHelper()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}

    /// <summary>
    /// 计算用户多身份的数据标志位
    /// </summary>
    /// <param name="UserID">用户编号(主)</param>
    /// <returns></returns>
    public static string getUserDataFlags(string UserID)
    {
        int result = 0;
        string sql = "select Code FROM a_eke_sysUsers where deltag=0 and Active=1 and (UserID='" + UserID + "' or ParentID='" + UserID + "')";
        DataTable tb = eBase.UserInfoDB.getDataTable(sql);
        foreach (DataRow dr in tb.Rows)
        {
            if (dr["Code"].ToString().Length == 0) continue;
            string tmp = getOrganizationDataFlags(dr["Code"].ToString());
            if (tmp == "0") continue;
            result = result == 0 ? Convert.ToInt32(tmp) : result | Convert.ToInt32(tmp);
        }
        return result.ToString();
    }
    /// <summary>
    /// 单个机构的数据标志位
    /// </summary>
    /// <param name="Code">机构编码</param>
    /// <returns></returns>
    public static string getOrganizationDataFlags(string Code)
    {
        string result = "0";
        DataTable tb = eBase.DataBase.getDataTable("select * from Organizationals where deltag=0");
        DataRow[] rs = tb.Select("Code='" + Code + "'");
        if (rs.Length == 0) return result;
        if (rs[0]["IsCorp"].ToString() == "True" && Convert.ToInt32(rs[0]["DataFlags"]) > 0)
        {
            return rs[0]["DataFlags"].ToString();
        }       

        rs = tb.Select("Code='" + rs[0]["ParentCode"].ToString() + "'");      
        while (rs.Length > 0)
        {
            if (rs[0]["IsCorp"].ToString() == "True" && Convert.ToInt32(rs[0]["DataFlags"]) > 0)
            {
                return rs[0]["DataFlags"].ToString();
            }
            rs = tb.Select("Code='" + rs[0]["ParentCode"].ToString() + "'");
         }
        return result;
    }
    public static void clearDataCache()
    {
        System.Web.Caching.Cache cache = HttpRuntime.Cache;
        IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
        while (CacheEnum.MoveNext())
        {
            cache.Remove(CacheEnum.Key.ToString());
        }
        eBase.DataBase.removePrimaryKeys();
        eBase.clearDataCache();
    }
    /// <summary>
    /// 用户登录日志
    /// </summary>
    /// <param name="user">用户对象</param>
    public static void UserLoginLog(eUser user)
    {
        eBase.UserInfoDB.Execute("update a_eke_sysUsers set LastLoginTime=isnull(LoginTime,getdate()) where UserID='" + user["id"] + "'");
        eBase.UserInfoDB.Execute("update a_eke_sysUsers set LoginCount=LoginCount+1,LoginTime=getdate() where UserID='" + user["id"] + "'");
        eTable etb = new eTable("a_eke_sysUserLog");
        etb.DataBase = eBase.UserInfoDB;
        etb.Fields.Add("SiteID", user["siteid"]);
        etb.Fields.Add("UserID", user["id"]);
        etb.Fields.Add("Type", 1);
        etb.Fields.Add("IP", eBase.getIP());
        etb.Fields.Add("Area", user.Area);
        string UserAgent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
        if (etb.Columns.Contains("UserAgent") && !string.IsNullOrEmpty(UserAgent))
        {            
            etb.Fields.Add("UserAgent", UserAgent);
        }
        etb.Add();

    }
    /// <summary>
    /// 用户退出日志
    /// </summary>
    /// <param name="user">用户对象</param>
    public static void UserLoginOutLog(eUser user)
    {
        eTable etb = new eTable("a_eke_sysUserLog");
        etb.DataBase = eBase.UserInfoDB;
        etb.Fields.Add("UserID", user["id"]);
        etb.Fields.Add("Type", 2);
        etb.Fields.Add("IP", eBase.getIP());
        etb.Fields.Add("Area", user.Area);
        etb.Add();
    }
    /// <summary>
    /// 更新错误次数
    /// </summary>
    public static void setErrorSession()
    {

        if (HttpContext.Current.Session["LoginErrorCount"] == null)
        {
            HttpContext.Current.Session["LoginErrorCount"] = 1;
        }
        else
        {
            HttpContext.Current.Session["LoginErrorCount"] = Convert.ToInt32(HttpContext.Current.Session["LoginErrorCount"]) + 1;
        }
    }
    /// <summary>
    /// 当前登录出错次数
    /// </summary>
    /// <returns></returns>
    public static int getErrorSession()
    {
        if (HttpContext.Current.Session["LoginErrorCount"] == null) return 0;
        return Convert.ToInt32(HttpContext.Current.Session["LoginErrorCount"]);
    }
    /// <summary>
    /// 检查登录错误次数是否超过设定值
    /// </summary>
    public static void checkErrorCount()
    {

        if (eConfig.loginErrorCount() > 0 && getErrorSession() > eConfig.loginErrorCount())
        {
            HttpContext.Current.Session.Remove("Plugins_RndCode");
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/html; charset=utf-8";
            HttpContext.Current.Response.Write("操作过于频繁,请稍后再试!");
            HttpContext.Current.Response.End();
        }
    }
    /// <summary>
    /// 验证验证码是否正确
    /// </summary>
    /// <param name="code">验证码</param>
    /// <param name="url">验证码不正确时的跳转连接</param>
    public static void checkRndCode(string code,string url)
    {
        if (eConfig.openRndCode())
        {
            if (HttpContext.Current.Session["Plugins_RndCode"] == null)
            {
                setErrorSession(); //增加登录错误次数
                HttpContext.Current.Response.Write("<script>alert('验证码超时！');document.location='" + url + "';</script>");
                HttpContext.Current.Response.End();
            }
            if (HttpContext.Current.Session["Plugins_RndCode"].ToString().ToLower() !=  code.ToLower())
            {
                setErrorSession(); //增加登录错误次数
                HttpContext.Current.Session.Remove("Plugins_RndCode");
                HttpContext.Current.Response.Write("<script>alert('验证码不正确！');document.location='" + url + "';</script>");
                HttpContext.Current.Response.End();
            }
            HttpContext.Current.Session.Remove("Plugins_RndCode");
        }
    }
    /// <summary>
    /// 保存用户信息
    /// </summary>
    /// <param name="user">用户对象</param>
    /// <param name="dr">用户数据行</param>
    public static void saveUserInfo(eUser user, DataRow dr)
    {

        user["id"] = dr["UserID"].ToString();
        if (dr.Table.Columns.Contains("usertype")) user["usertype"] = dr["usertype"].ToString();//用户类型
        user["user"] = dr["YHM"].ToString();
        user["name"] = dr["XM"].ToString();
        if (dr.Table.Columns.Contains("school_id") && dr["school_id"].ToString().Length > 0) user["school_id"] = dr["school_id"].ToString();

        if (dr.Table.Columns.Contains("nick") && dr["nick"].ToString().Length > 0) user["nick"] = dr["nick"].ToString();
        if (dr.Table.Columns.Contains("webCode") && dr["webCode"].ToString().Length > 0) user["webCode"] = dr["webCode"].ToString();
        user["roleid"] = dr["RoleID"].ToString();
        user["userroleid"] = dr["RoleID"].ToString();
        user["siteid"] = dr["siteid"].ToString() == "0" ? "1" : dr["siteid"].ToString();

        user["face"] = eBase.getVirtualPath() + (dr["face"].ToString().Length > 10 ? dr["face"].ToString() : "images/head.png"); //用户头像
        if (HttpContext.Current.Request.Form["appids"] != null) user["appids"] = HttpContext.Current.Request.Form["appids"].ToString();//应用


        if (dr.Table.Columns.Contains("Department") && dr["Department"].ToString().Length > 0) user["depname"] = dr["Department"].ToString();//部门名称
        if (dr.Table.Columns.Contains("openid") && dr["openid"].ToString().Length > 0) user["openid"] = dr["openid"].ToString();
        if (dr.Table.Columns.Contains("usercode") && dr["usercode"].ToString().Length > 0) user["usercode"] = dr["usercode"].ToString(); //当前登录用户编码
        if (dr.Table.Columns.Contains("code") && dr["code"].ToString().Length > 0) user["orgcode"] = dr["code"].ToString(); //当前登录用户机构编码      
        if (dr.Table.Columns.Contains("ServiceID") && dr["ServiceID"].ToString().Length > 0) user["ServiceID"] = dr["ServiceID"].ToString();

        if (dr.Table.Columns.Contains("PostLevel")) //职位等级 (升序:职务越高数值越小)
        {
            user["PostLevel"] =  dr["PostLevel"].ToString() == "0" ? "99" : dr["PostLevel"].ToString();
        }
        //if (dr.Table.Columns.Contains("DataFlags") && dr["DataFlags"].ToString().Length > 0) user["DataFlags"] = dr["DataFlags"].ToString();

        user["DataFlags"] = getUserDataFlags(dr["UserID"].ToString()).ToString();

        foreach (JsonData item in eConfig.saveUserInfo)
        {
         
            string name = item.getValue("name");
            string value = item.getValue("value");

            //eBase.Writeln(name + "::" + value);
            if (name.Length == 0 || value.Length == 0) continue;
            if (dr.Table.Columns.Contains(value))  // && dr[value].ToString().Length > 0
            {
                user[name] = dr[value].ToString();
            }
        }
        //eBase.Print(user);
        //eBase.End();
        user.Save();
    }
    /// <summary>
    /// 统一的模块处理过程
    /// </summary>
    /// <param name="model">模块</param>
    /// <param name="LitBody">转出控件</param>
    public static void modelHandle(eModel model, Literal LitBody)
    {
        
        /*
        switch (model.Action.Value)
        {
            case "version":
                LitBody.Text = model.getVersion();
                break;
            case "setfixed": //设置和取消浮动
                #region 设置和取消浮动
                string name = eParameters.QueryString("name");
                string value = eParameters.QueryString("value");
                string type = name == "application_left_fixed" ? "左侧固定" : "顶部固定";
                if (name == "application_left_fixed")
                {
                    HttpContext.Current.Session.Remove("Application_LeftFixed");
                }
                else
                {
                    HttpContext.Current.Session.Remove("Application_TopFixed");
                }
                string sql = "if exists (select * from a_eke_sysUserCustoms Where parName='" + name + "' and UserID='" + model.User.ID + "')";
                sql += "update a_eke_sysUserCustoms set parValue='" + value + "' where parName='" + name + "' and UserID='" + model.User.ID + "'";
                sql += " else ";
                sql += "insert into a_eke_sysUserCustoms (UserID,parName,MC,parValue) ";
                sql += " values ('" + model.User.ID + "','" + name + "','" + type + "','" + value + "')";
                eBase.UserInfoDB.Execute(sql);
                eBase.End();
                #endregion
                break;
            case "delmore": //批量删除
                #region 批量删除
                string ids = eParameters.QueryString("ids");
                string[] arrs = ids.Split(",".ToCharArray());
                ids = "'" + ids.Replace(",", "','") + "'";
                eTable etb = new eTable(model.eForm.TableName, model.User);
                etb.Where.Add(model.eForm.primaryKey + " in (" + ids + ")");
                etb.Delete();
                //etb.DeleteTrue();

                sql = model.ModelInfo["DeleteSql"].ToString();
                if (sql.Length > 0)
                {
                    foreach (string _id in arrs)
                    {
                        DataTable tb = new DataTable();
                        tb.Columns.Add("ID", typeof(string));

                        DataRow dr = tb.NewRow();
                        dr["ID"] = _id;
                        string _sql = eParameters.Replace(sql, dr, model.User,true);
                        model.DataBase.ExecuteMore(_sql);
                    }
                }
                HttpContext.Current.Response.Redirect(HttpContext.Current.Request.UrlReferrer.PathAndQuery, true);
                #endregion
                break;
            case "building": //未建设完成模块
                LitBody.Text = "<div style=\"padding:50px; height:100%; text-align:center; \"><img src=\"../images/Building.jpg\" style=\"width:390px;\" /></div>";
                break;

            case "": //列表
                if (model.ModelInfo["type"].ToString() == "4")//报表
                {
                    LitBody.Text = model.getReportList();
                }
                else //列表
                {
                    LitBody.Text = model.getListHTML();
                }
                break;
            case "add": //添加
                LitBody.Text = model.getAddHTML();
                break;
            case "edit": //编辑
                LitBody.Text = model.getEditHTML();
                break;
            case "copy": //复制
                LitBody.Text = model.getEditHTML();
                break;
            case "view": //查看
                LitBody.Text = model.getViewHTML();
                break;
            case "print": //打印
                eBase.Write(model.getPrintHTML());
                eBase.End();
                break;
            case "save": //保存
                model.Save();
                break;
            case "del": //删除
                model.Delete();
                break;
            case "addsub": //子模块添加
                eBase.Write(model.getAddHTML());
                eBase.End();
                break;
            case "viewsub": //子模块查看
                eBase.Write(model.getViewHTML());
                eBase.End();
                break;
            case "export": //导出
                model.ExportExcel();
                break;
            case "getrole": //获取用户、角色权限
                string roleid = eParameters.QueryString("roleid");
                string userid = eParameters.QueryString("id");
                DataTable rolePower = eBase.getUserPower(roleid, userid);
                eBase.Write(rolePower.toJSON());
                eBase.End();
                break;
        }
        */
    }
}
